import React, {Component, useEffect, useRef, useState} from "react";
import classNames from "classnames";
import "./Swiper.scss"

type SwiperProps = {
    list: string[],
    autoplay: boolean,
    interval: number
}

const Swiper: React.MemoExoticComponent<(props: SwiperProps) => React.ReactElement> = React.memo((props: SwiperProps) => {
    const [activeIndex, setActiveIndex] = useState<number>(0);
    const time = useRef<NodeJS.Timeout>()
    const [isShowButton, setIsHowButton] = useState(false)

    const {list, autoplay, interval} = props

    const handlePrev = (): void => {
        setActiveIndex(activeIndex - 1);
        if (activeIndex <= 0) {
            setActiveIndex(list.length - 1);
        }
    }

    const handleNext = (): void => {
        setActiveIndex(activeIndex + 1);
        if (activeIndex >= list.length - 1) {
            setActiveIndex(0);
        }
    }

    const handleAutoCarousel = () => {
        if (!autoplay) return
        clearInterval(time.current);
        time.current = setInterval(() => {
            setActiveIndex(activeIndex + 1)
            if (activeIndex >= list.length - 1) {
                setActiveIndex(0)
            }
        }, interval)
    }

    const handleEnter = () => {
        clearInterval(time.current);
        setIsHowButton(true)
    }

    const handleLeave = () => {
        handleAutoCarousel()
        setIsHowButton(false)
    }

    useEffect(() => {
        handleAutoCarousel()
    }, [activeIndex])

    return (
        <div className="swiper" onMouseEnter={handleEnter} onMouseLeave={handleLeave}>

            {list.map((item, index) => <div className={classNames('swiper-item', index === activeIndex ? 'active' : '')} key={index}><img src={item} alt=""/></div>)}

            {
                isShowButton && <div className="prev" onClick={handlePrev}><i className="iconfont icon-zuo"></i></div>
            }
            {
                isShowButton && <div className="next" onClick={handleNext}><i className="iconfont icon-you"></i></div>
            }

            <ul className="point">{list.map((item, index) => <li key={index} className={classNames(index === activeIndex ? 'active' : '')}></li>)}</ul>

        </div>
    )
})

export default Swiper
